package com.guosen.zebra.framework.starter.ngx.internal.impl;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public final class UniNgxUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(UniNgxUtil.class);

    /**
     * Authorization头
     */
    private static final String HEADER_AUTHORIZATION = "Authorization";

    /**
     * 正常返回码
     */
    private static final String OK_CODE = "200";

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    private UniNgxUtil(){}

    public static Map<String, String> buildHeaders(InvokeContext invokeContext) {
        Map<String, String> headers = new HashMap<>();
        headers.put(HEADER_AUTHORIZATION, invokeContext.getToken());
        return headers;
    }

    public static void addParameter(Map<String, String> parameters, String key, Object val) {
        if (val == null) {
            return;
        }

        parameters.put(key, String.valueOf(val));
    }


    public static String urlEncodePath(String path) {
        String[] pathItems = StringUtils.split(path, "/");
        for (int i = 0; i < pathItems.length; i++) {
            pathItems[i] = UrlEncodeDecoder.encode(pathItems[i]);
        }
        return "/" + StringUtils.joinWith("/", pathItems);
    }

    /**
     * 获取ObjectMapper，提升性能
     * @return  ObjectMapper
     */
    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    public static void raiseExceptionIfExist(JsonNode result) throws NgxException {
        result.get("code").asText();
        String code = result.get("code").asText();
        String msg = result.get("msg").asText();
        if (!OK_CODE.equals(code)) {
            LOGGER.error("Return failed, code : {}, msg : {}", code, msg);
            throw new NgxException(code, msg);
        }
    }
}
